
//
//  WBNetworkManager+Extension.swift
//  WeiboSwift
//
//  Created by hfwd on 2017/5/22.
//  Copyright © 2017年 hfwd. All rights reserved.
//

import Foundation

// MARK: - 获取token的请求
extension WBNetworkManager {
    
    /// 获取token的请求
    ///
    /// - Parameters:
    ///   - code: 登录获取的URL后面的code
    ///   - completion: 完成回调（登录令牌，返回数据是否成功）
    func loadAccessTokenRequest(code: String, completion:@escaping (_ acceccToken: String, _ isSuccess: Bool)->()) {
        
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": WBAppKey, "client_secret": WBAppSecret, "grant_type": "authorization_code", "code": code, "redirect_uri": WBRedirectURL]
        
        request(Method: .POST, URLString: urlStr, parameters: params as [String : AnyObject]?) { (json, isSuccess) in
            
            self.userAccount.yy_modelSet(with: (json as? [String : AnyObject]) ?? [:])
            
            self.userAccount.saveUserAccount()
            
            let result = json?["access_token"] as? String
            
            self.loadUserInfo(completion: { (dict) in

                self.userAccount.yy_modelSet(with: (dict))
                
                self.userAccount.saveUserAccount()
                
                completion(result ?? "", isSuccess)
            })
            
            
        }
    }
}

// MARK: - 封装微博数据的网络请求方法
extension WBNetworkManager {
    
    /// 获取首页微博数据
    ///
    /// - Parameters:
    ///   - since_id: 开始的id
    ///   - max_id: 最大的id
    ///   - completion: 完成回调（微博字典数组，返回数据是否成功）
    func statusList(since_id: Int64, max_id: Int64, completion:@escaping ((_ list:  [[String : AnyObject]]?, _ isSuccess: Bool)->())) {
        
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let params = ["since_id": "\(since_id)",
            "max_id": "\((max_id > 0) ? (max_id - 1) : 0)"]

        tokenRequest(Method: .GET, URLString: urlStr, parameters: params as [String : AnyObject]?) { (json, isSuccess) in

            let result = json?["statuses"] as? [[String : AnyObject]]
            
            completion(result, isSuccess)
        }
    }
}


// MARK: - 获取用户未读的新微博数
extension WBNetworkManager {
    
    /// 获取用户未读的新微博数
    ///
    /// - Parameter completion: 完成回调（未读微博数，返回数据是否成功）
    func unreadCount(completion:@escaping (_ count: Int, _ isSuccess: Bool)->()) {
        
        guard let uid = userAccount.uid else {
            return
        }
        
        let urlStr = "https://rm.api.weibo.com/2/remind/unread_count.json"
        
        let params = ["uid" : uid]
        
        tokenRequest(URLString: urlStr, parameters: params as [String : AnyObject]?) { (json, isSuccess) in
            
            let dict = json as? [String : AnyObject]
            
            let count = dict?["status"] as? Int
            
            completion(count ?? 0 , isSuccess)
        }
    }
}

// MARK: - 获取用户的信息
extension WBNetworkManager {
    
    /// 获取用户的信息
    ///
    /// - Parameter completion: 完成回调(用户信息字典）
    func loadUserInfo(completion: @escaping (_ result:[String : AnyObject]) -> ()) {
        
        guard let uid = userAccount.uid else {
            return
        }
        
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        let params = ["uid" : uid]
        
        tokenRequest(URLString: urlStr, parameters: params as [String : AnyObject]?) { (json, isSuccess) in
            
            let result = json as? [String : AnyObject] ?? [:]
            
            completion(result)
        }
    }
}

